package com.guaoran.source.dubbo.spi;


import com.alibaba.dubbo.common.URL;
import com.alibaba.dubbo.common.extension.ExtensionLoader;
import com.alibaba.dubbo.rpc.Exporter;
import com.alibaba.dubbo.rpc.Invoker;
import com.alibaba.dubbo.rpc.Protocol;
import com.alibaba.dubbo.rpc.RpcException;

/**
 * @author : guaoran
 * @Description : <br/>
 *  根据 createAdaptiveExtensionClass() 动态获得的 适配器扩展点
 * @date :2019/1/7 13:31
 */
public class Protocol$Adpative implements Protocol {
    public void destroy() {
        throw new UnsupportedOperationException("method public abstract void Protocol.destroy() of interface Protocol is not adaptive method!");
    }

    public int getDefaultPort() {
        throw new UnsupportedOperationException("method public abstract int Protocol.getDefaultPort() of interface Protocol is not adaptive method!");
    }
    //服务发布
    public Exporter export(Invoker arg0) throws RpcException {
        if (arg0 == null) throw new IllegalArgumentException("Invoker argument == null");
        if (arg0.getUrl() == null)
            throw new IllegalArgumentException("Invoker argument getUrl() == null");
        //当url=registry://192.168.45.123....时，extension = RegistryProtocol
        URL url = arg0.getUrl();
        String extName = (url.getProtocol() == null ? "dubbo" : url.getProtocol());
        if (extName == null)
            throw new IllegalStateException("Fail to get extensionProtocol) name from url(" + url.toString() + ") use keys([protocol])");
        // 当url=registry://192.168.45.1...时，extension = ProtocolFilterWrapper(ProtocolListenerWrapper(RegistryProtocol))
        // 当url=dubbo://192.168.45.1...时，extension = ProtocolFilterWrapper(ProtocolListenerWrapper(DubboProtocol)) ,
        // todo 为什么 extension 不是 [DubboProtocol] ,
        // todo 因为 在 Protocol 进行loadFile 的时候，会加载 到 clazz.getConstructor(type); 不报错， 则 cachedWrapperClasses 不为空,
        // todo 所以 在 getExtension("dubbo") 的时候会首先获得 DubboProtocol ，然后会进行封装成 wrapper
        Protocol extension = (Protocol) ExtensionLoader.getExtensionLoader(Protocol.class).getExtension(extName);
        return extension.export(arg0);
    }

    public Invoker refer(Class arg0, URL arg1) throws RpcException {
        if (arg1 == null) throw new IllegalArgumentException("url == null");
        URL url = arg1;
        String extName = (url.getProtocol() == null ? "dubbo" : url.getProtocol());
        if (extName == null)
            throw new IllegalStateException("Fail to get extension(Protocol) name from url(" + url.toString() + ") use keys([protocol])");
        Protocol extension = (Protocol) ExtensionLoader.getExtensionLoader(Protocol.class).getExtension(extName);
        return extension.refer(arg0, arg1);
    }
}
